using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace Microsoft.Vsts.Ranger.Migration.TfsToTfs.Client.Controls
{
    public partial class TeamProjectPicker : UserControl
    {
        private string _serverUri;
        private string _serverName = "";

        public TeamProjectPicker()
        {
            InitializeComponent();
        }


        public string GroupBoxTitle
        {
            get { return grpSourceProject.Text; }
            set { grpSourceProject.Text = value; }
        }

        public string ServerName
        {
            get 
            {
                if (_serverName.Length == 0)
                {
                    _serverName = GetHostNameFromServerName(txtSourceServerName.Text).ToLower();
                }

                return _serverName;
            }
        }

        public string TeamProjectName
        {
            get { return cmbSourceProjectName.Text; }
        }

        public bool UseStoredCredential
        {
            get { return chkUseStoredCred.Checked; }
        }

        public string ServerUri
        {
            get { return _serverUri; }
        }

        public bool ValidSelectionState
        {
            get 
            {
                if (ServerName.Length > 0 && TeamProjectName.Length > 0)
                    return true;
                else
                    return false;
            }
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            cmbSourceProjectName.Items.Clear();

            TfsHelper tfsHelper = new TfsHelper();

            if (tfsHelper.TfsConnect(txtSourceServerName.Text, chkUseStoredCred.Checked))
            {

                cmbSourceProjectName.Enabled = true;
                //cmbSourceProjectName.DataSource = tfsHelper.GetTeamProjects();

                foreach (string item in tfsHelper.GetTeamProjects())
                    cmbSourceProjectName.Items.Add(item);

                cmbSourceProjectName.Refresh();

                _serverUri = tfsHelper.GetServerUri();
            }
            else
            {
                cmbSourceProjectName.Enabled = false;
            }
        }

        private string GetHostNameFromServerName(string serverName)
        {
            if (Uri.IsWellFormedUriString(serverName, UriKind.Absolute))
            {
                Uri uri = new Uri(serverName);

                return uri.Host;
            }
            else
            {
                return serverName;
            }
        }


    }
}
